package com.haierp.service.youzan.impl;

import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;

import org.eclipse.jetty.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.haierp.enums.OrderStatus;
import com.haierp.enums.PayType;
import com.haierp.enums.PlatformType;
import com.haierp.mapper.ItemMapper;
import com.haierp.mapper.ItemSkuMapper;
import com.haierp.mapper.OuterItemMapper;
import com.haierp.mapper.OuterItemSkuMapper;
import com.haierp.mapper.OuterOrderDetailMapper;
import com.haierp.mapper.OuterOrderMapper;
import com.haierp.model.Inventory;
import com.haierp.model.Item;
import com.haierp.model.ItemSku;
import com.haierp.model.item.OuterItem;
import com.haierp.model.sale.OuterOrder;
import com.haierp.model.sale.OuterOrderDetail;
import com.haierp.model.youzan.YouzanTradesSoldGet;
import com.haierp.model.youzan.YouzanTradesSoldGetResult;
import com.haierp.model.youzan.YouzanTradesSoldGetResult.StructurizationTrade;
import com.haierp.model.youzan.YouzanTradesSoldGetResult.StructurizationTradeItemDetail;
import com.haierp.service.IInventoryService;
import com.haierp.service.IItemSkuService;
import com.haierp.service.ISequenceUtilService;
import com.haierp.service.IUploadFileService;
import com.haierp.service.item.IOuterItemService;
import com.haierp.service.youzan.IYouzanService;
import com.haierp.util.DateUtil;
import com.haierp.util.DimensionCodeUtil;
import com.youzan.open.sdk.client.auth.Token;
import com.youzan.open.sdk.client.core.DefaultYZClient;
import com.youzan.open.sdk.gen.v3_0_0.api.YouzanItemcategoriesGet;
import com.youzan.open.sdk.gen.v3_0_0.api.YouzanItemcategoriesTagsGet;
import com.youzan.open.sdk.gen.v3_0_0.api.YouzanItemsInventoryGet;
import com.youzan.open.sdk.gen.v3_0_0.model.YouzanItemcategoriesGetParams;
import com.youzan.open.sdk.gen.v3_0_0.model.YouzanItemcategoriesGetResult;
import com.youzan.open.sdk.gen.v3_0_0.model.YouzanItemcategoriesGetResult.Categories;
import com.youzan.open.sdk.gen.v3_0_0.model.YouzanItemcategoriesTagsGetParams;
import com.youzan.open.sdk.gen.v3_0_0.model.YouzanItemcategoriesTagsGetResult;
import com.youzan.open.sdk.gen.v3_0_0.model.YouzanItemcategoriesTagsGetResult.ItemGroupOpenModel;
import com.youzan.open.sdk.gen.v3_0_0.model.YouzanItemsInventoryGetParams;
import com.youzan.open.sdk.gen.v3_0_0.model.YouzanItemsInventoryGetResult;
import com.youzan.open.sdk.gen.v3_0_0.model.YouzanItemsInventoryGetResult.ItemListOpenModel;
import com.youzan.open.sdk.gen.v4_0_0.model.YouzanTradesSoldGetParams;

import net.sf.json.JSONObject;

@Service("youzanService")
public class YouzanServiceImpl implements IYouzanService {
	@Autowired
	private ISequenceUtilService sequenceUtilService;

	@Autowired
	private OuterOrderMapper outerOrderMapper;

	@Autowired
	private OuterOrderDetailMapper outerOrderDetailMapper;

	@Autowired
	OuterItemMapper outerItemMapper;

	@Autowired
	OuterItemSkuMapper outerItemSkuMapper;

	@Autowired
	ItemMapper itemMapper;

	@Autowired
	ItemSkuMapper itemSkuMapper;

	private DefaultYZClient yzClient;

	@Autowired
	private IInventoryService inventoryService;

	@Autowired
	private IItemSkuService itemSkuService;

	@Autowired
	private IOuterItemService outerItemService;

	@Autowired
	private IUploadFileService uploadFileService;

	public YouzanServiceImpl(String clientId, String clientSecret, String kdtId) {
		if(StringUtil.isBlank(DimensionCodeUtil.youZanToken)) {
			DimensionCodeUtil.setClientKey(clientId, clientSecret, kdtId);
			DimensionCodeUtil.getYouZanToken();
		}
		yzClient = new DefaultYZClient(new Token(DimensionCodeUtil.youZanToken));
	}

	/**
	 * 添加订单
	 */
	@Override
	public List<Long> youzanTradesAdd() {
		//交易状态更新的结束时间,值为当前时间
		Date EndUpdate = new Date();
		//交易状态更新的开始时间,值为当前时间的1个小时前，因为定时任务设置为半个小时,这样每个订单会有2次抓取机会
		Date StartUpdate = DateUtil.getDateByCalculate(EndUpdate, Calendar.HOUR_OF_DAY, -1);
		return youzanTradesAdd(StartUpdate, EndUpdate);
	}
	
	@Override
	public List<Long> youzanTradesAdd(Date StartUpdate, Date endUpdate) {
		//方法
		YouzanTradesSoldGet youzanTradesSoldGet = new YouzanTradesSoldGet();
		//参数
		YouzanTradesSoldGetParams youzanTradesSoldGetParams = new YouzanTradesSoldGetParams();
		//买家已付款，等待发货
		youzanTradesSoldGetParams.setStatus("WAIT_SELLER_SEND_GOODS");
		youzanTradesSoldGetParams.setStartUpdate(StartUpdate);
		youzanTradesSoldGetParams.setEndUpdate(endUpdate);
		youzanTradesSoldGetParams.setPageSize(100L);

		boolean hasNext = true;
		long pageNo = 1L;
		List<Long> outOrderIdList = new ArrayList<Long>();
		while(hasNext) {
			youzanTradesSoldGetParams.setPageNo(pageNo);
			youzanTradesSoldGet.setAPIParams(youzanTradesSoldGetParams);
			YouzanTradesSoldGetResult result = yzClient.invoke(youzanTradesSoldGet);
			//设置循环
			pageNo++;
			if(result.getFullOrderInfoList().length==0 || pageNo==101) {
				break;
			}

			StructurizationTrade[] fullOrderInfoList = result.getFullOrderInfoList();
			for(int i=fullOrderInfoList.length-1; i>=0; i--) {
				StructurizationTrade fullOrderInfo = fullOrderInfoList[i];
				//如果有赞订单已存在，略过
				OuterOrder p = new OuterOrder();
				p.setTargetNo(fullOrderInfo.getFullOrderInfo().getOrderInfo().getTid());
				if(outerOrderMapper.selectCount(p) > 0) {
					continue;
				}

				//如果有赞订单还不存在，继续
				OuterOrder outerOrder = new OuterOrder();
				//有赞平台为01,销售为0000
				outerOrder.setCompanyId(1L);//有赞下单更改所属公司
				outerOrder.setOrderNo("P"+String.format("%0"+2+"d", 1)+String.format("%0"+4+"d", 4)+"D"+DateUtil.formatDate(fullOrderInfo.getFullOrderInfo().getOrderInfo().getPayTime(), DateUtil.DATE_PARTEN_YYMMDDHHMMSS)+sequenceUtilService.gainORDSequence());	//系统自动生成
				outerOrder.setOrderTime(fullOrderInfo.getFullOrderInfo().getOrderInfo().getPayTime());					    //付款时间
				outerOrder.setStatus(OrderStatus.INIT.getCode());															//状态：新建
				outerOrder.setReceiver(fullOrderInfo.getFullOrderInfo().getAddressInfo().getReceiverName());				//收货人
				outerOrder.setReceiverState(fullOrderInfo.getFullOrderInfo().getAddressInfo().getDeliveryProvince());		//省
				outerOrder.setReceiverCity(fullOrderInfo.getFullOrderInfo().getAddressInfo().getDeliveryCity());			//市
				outerOrder.setReceiverDistrict(fullOrderInfo.getFullOrderInfo().getAddressInfo().getDeliveryDistrict());	//区
				outerOrder.setAddressDetail(fullOrderInfo.getFullOrderInfo().getAddressInfo().getDeliveryAddress());	    //详细地址
				outerOrder.setTelephone(fullOrderInfo.getFullOrderInfo().getAddressInfo().getReceiverTel());			    //联系电话
				outerOrder.setPostcode(fullOrderInfo.getFullOrderInfo().getAddressInfo().getDeliveryPostalCode());		    //邮编
				outerOrder.setRemark(fullOrderInfo.getFullOrderInfo().getRemarkInfo().getBuyerMessage());				    //买家购买附言
				outerOrder.setTargetNo(fullOrderInfo.getFullOrderInfo().getOrderInfo().getTid());						    //有赞平台交易编号
				outerOrder.setIdCard(fullOrderInfo.getFullOrderInfo().getOrderInfo().getOrderExtra().getIdCardNumber());    //身份证
				outerOrder.setPlatformType(PlatformType.YOUZAN.getCode());													//销售来源(平台)
				if(StringUtil.isNotBlank(fullOrderInfo.getFullOrderInfo().getOrderInfo().getPayTypeStr())) {
					outerOrder.setPayType(PayType.valueOf(fullOrderInfo.getFullOrderInfo().getOrderInfo().getPayTypeStr()).getCode());								//支付方式
				}
				outerOrder.setUserCreate("定时任务");									//创建者
				//outerOrder.setUserModify("定时任务");								//修改者
				outerOrder.setGmtCreate(fullOrderInfo.getFullOrderInfo().getOrderInfo().getCreated());					//创建时间
				outerOrder.setGmtModify(fullOrderInfo.getFullOrderInfo().getOrderInfo().getUpdateTime());				//修改时间
				outerOrder.setSalesName("有赞");
				outerOrder.setSalesId(4L);
				outerOrderMapper.insert(outerOrder);								//添加主订单

				outOrderIdList.add(outerOrder.getId());								//收集主订单ID

				StructurizationTradeItemDetail[] ordersArr = fullOrderInfo.getFullOrderInfo().getOrders();
				List<OuterOrderDetail> outerOrderDetails = new ArrayList<OuterOrderDetail>();
				String ConsigneeIDFrontUrl = null;	//身份证正面url
				String ConsigneeIDBackUrl = null;	//身份证反面url
				for(int j=0; j<ordersArr.length; j++) {
					StructurizationTradeItemDetail ordersDetail = ordersArr[j];

					OuterOrderDetail outerOrderDetail = new OuterOrderDetail();
					outerOrderDetail.setOuterOrderId(outerOrder.getId());			//主订单ID
					outerOrderDetail.setCompanyId(outerOrder.getCompanyId());       // 订单所属公司
					outerOrderDetail.setSkuCode(ordersDetail.getOuterSkuId());		//sku编码
					outerOrderDetail.setSalePrice(Double.parseDouble(String.valueOf(ordersDetail.getPrice())));	//商品单价
					outerOrderDetail.setQuantity(Integer.parseInt(String.valueOf(ordersDetail.getNum())));	    //购买数量
					outerOrderDetail.setOid(String.valueOf(ordersDetail.getOid())); //商品交易明细编号
					outerOrderDetail.setGmtCreate(fullOrderInfo.getFullOrderInfo().getOrderInfo().getCreated());		//创建时间
					outerOrderDetail.setGmtModify(fullOrderInfo.getFullOrderInfo().getOrderInfo().getUpdateTime());		//修改时间
					outerOrderDetails.add(outerOrderDetail);

					if(StringUtil.isNotBlank(ordersDetail.getBuyerMessages()) && StringUtil.isBlank(ConsigneeIDFrontUrl)) {
						JSONObject  jasonObject = JSONObject.fromObject(ordersDetail.getBuyerMessages());
						Map map = (Map)jasonObject;
						ConsigneeIDFrontUrl = (String)map.get("身份证正面");
						ConsigneeIDBackUrl = (String)map.get("身份证反面");
						if(StringUtil.isNotBlank(ConsigneeIDFrontUrl)) {
							ConsigneeIDFrontUrl = getAliyunImageUrl(ConsigneeIDFrontUrl);
						}
						if(StringUtil.isNotBlank(ConsigneeIDBackUrl)) {
							ConsigneeIDBackUrl = getAliyunImageUrl(ConsigneeIDBackUrl);
						}
					}

					//如果有虚拟库存就扣减虚拟库存
					ItemSku tjItemSku = new ItemSku();
					tjItemSku.setSkuCode(ordersDetail.getOuterSkuId());
					ItemSku itemSku = itemSkuService.selectOne(tjItemSku);
					if(itemSku != null) {
						Inventory inventory = inventoryService.queryInventoryBySkuId(itemSku.getItemId(), itemSku.getId());
						if(inventory.getVirtualInv()>0) {
							int virtualInv = inventory.getVirtualInv() - outerOrderDetail.getQuantity();
							virtualInv = virtualInv>0 ? virtualInv : 0;
							//如果虚拟库存小于等于可售库存，虚拟库存清零
							virtualInv = virtualInv>inventory.getTotalAvailableInv() ? virtualInv : 0;

							//如果虚拟占用库存大于零，有赞下单不应该减少虚拟预扣
							/*if(inventory.getLockedVirtualInv() > 0) {
								int lockedVirtualInv = inventory.getLockedVirtualInv() - outerOrderDetail.getQuantity();
								lockedVirtualInv = lockedVirtualInv>0 ? lockedVirtualInv : 0;
								inventory.setLockedVirtualInv(lockedVirtualInv);
							}*/
							inventory.setCompanyId(itemSku.getCompanyId());//所属
							inventory.setVirtualInv(virtualInv);
							inventory.setGmtModify(new Date());
							inventoryService.updateSelectiveById(inventory);
						}
					}
				}
				outerOrderDetailMapper.insertBatch(outerOrderDetails);				//添加子订单

				if(StringUtil.isNotBlank(ConsigneeIDFrontUrl) && StringUtil.isNotBlank(ConsigneeIDBackUrl)) {
					outerOrder.setIdcardPicFront(ConsigneeIDFrontUrl);
					outerOrder.setIdcardPicReverse(ConsigneeIDBackUrl);
					outerOrderMapper.updateSelectiveById(outerOrder);
				}
			}
		}
		if(outOrderIdList.size() > 0) {
			//把商品详情更新到主订单明细里面
			outerOrderDetailMapper.updateOuterOrderDetailByItemSku(outOrderIdList);
		}
		return outOrderIdList;
	}
	
	/**
	 * 获取有赞售罄中商品，然后下架
	 */
	@Override
	public void youzanSaleOutItemToDelisting() {
		int jiishu = 0;
		Long pageNo = 1L;
		while(true) {
			YouzanItemsInventoryGet youzanItemsInventoryGet = new YouzanItemsInventoryGet();
			YouzanItemsInventoryGetParams youzanItemsInventoryGetParams = new YouzanItemsInventoryGetParams();
			youzanItemsInventoryGetParams.setBanner("sold_out");
			youzanItemsInventoryGetParams.setPageSize(100L);
			youzanItemsInventoryGetParams.setPageNo(pageNo);
			youzanItemsInventoryGet.setAPIParams(youzanItemsInventoryGetParams);
			YouzanItemsInventoryGetResult result = yzClient.invoke(youzanItemsInventoryGet);
			ItemListOpenModel[] goodsDetails  = result.getItems();
			//System.out.println("=============================================pageNo：" + pageNo + "-" + goodsDetails.length);
			if(goodsDetails.length == 0) break;
			pageNo++;
			for(int i=0; i<goodsDetails.length; i++) {
				ItemListOpenModel goodsDetail = goodsDetails[i];
				if(goodsDetail.getQuantity() <= 0) {	//如果总库存小于等于零，下架
					jiishu++;
					OuterItem tjOuterItem = new OuterItem();
					tjOuterItem.setOuterId(goodsDetail.getItemId());
					OuterItem selOuterItem = outerItemMapper.selectOne(tjOuterItem);
					if(selOuterItem != null) {
						Item item = itemMapper.selectById(selOuterItem.getItemId());
						outerItemService.delistingYouzan(item);
					}
				}
			}
		}
		System.out.println("售罄中商品下架数==========>" + jiishu);
	}
	
	/**
	 * 获取商品类目列表
	 */
	@Override
	public void youzanItemcategoriesGet() {
		//方法
		YouzanItemcategoriesGet youzanItemcategoriesGet = new YouzanItemcategoriesGet();
		//参数
		YouzanItemcategoriesGetParams youzanItemcategoriesGetParams = new YouzanItemcategoriesGetParams();
		youzanItemcategoriesGet.setAPIParams(youzanItemcategoriesGetParams);
		YouzanItemcategoriesGetResult result = yzClient.invoke(youzanItemcategoriesGet);
		Categories[] goodsCategoryArr = result.getCategories();
		for(Categories g : goodsCategoryArr) {
			System.out.println(g.getCid() + ":" + g.getName());
		}
	}
	
	/**
	 * 查询商品分组
	 */
	@Override
	public void youzanItemcategoriesTagsGet() {
		//方法
		YouzanItemcategoriesTagsGet youzanItemcategoriesTagsGet = new YouzanItemcategoriesTagsGet();
		//参数
		YouzanItemcategoriesTagsGetParams youzanItemcategoriesTagsGetParams = new YouzanItemcategoriesTagsGetParams();
		youzanItemcategoriesTagsGet.setAPIParams(youzanItemcategoriesTagsGetParams);
		YouzanItemcategoriesTagsGetResult result = yzClient.invoke(youzanItemcategoriesTagsGet);
		ItemGroupOpenModel[] goodsTagArr = result.getTags();
		for(ItemGroupOpenModel g : goodsTagArr) {
			System.out.println(g.getId() + ":" + g.getName());
		}
	}
	
	/**
	 * 把普通图片路径转换成阿里云图片路径
	 */
	@Override
	public String getAliyunImageUrl(String picUrl) {
		try {
			URL urlImg  = new URL(picUrl);
			URLConnection con = urlImg.openConnection();
			con.setConnectTimeout(10*1000);
			StringBuilder sb = new StringBuilder();
			String end = picUrl.substring(picUrl.lastIndexOf(".")+1);
			sb.append(System.currentTimeMillis()).append("_").append((int) (Math.random() * 100)).append(".").append(end);
			picUrl = uploadFileService.uploadImgCard(con.getInputStream(), sb.toString());
			picUrl = picUrl + "?x-oss-process=image/quality,q_70";
			return picUrl;
		} catch (Exception e) {
			return null;
		} 
	}
}
